package com.wl156.activities;

import java.io.IOException;
import java.util.List;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.xmlpull.v1.XmlPullParserException;

import com.wl156.MyApp;
import com.wl156.R;
import com.wl156.activities.find.FindGood;
import com.wl156.activities.find.FindPlace;
import com.wl156.activities.order.GetMyCar;
import com.wl156.activities.order.GetMyGood;
import com.wl156.model.Certificate;
import com.wl156.model.User;
import com.wl156.model.WebServiceClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class My156 extends Activity implements OnClickListener {

	User mCurrentUser;
	LocationManager locationManager;
	private String myLongitude = "";
	private String myLatitude = "";

	private TextView mBalance;

	private WebServiceClient mWebServiceClient;
	private Certificate mCertificate;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.act_my_156);

		mWebServiceClient = new WebServiceClient(this);
		mCertificate = ((MyApp) getApplication()).getCertificateFromXml();
		try {
			mBalance = (TextView) findViewById(R.id.balance);

			findViewById(R.id.ziliaoweihu).setOnClickListener(this);
			findViewById(R.id.xiugaimima).setOnClickListener(this);
			findViewById(R.id.zhaohuimima).setOnClickListener(this);
			findViewById(R.id.cheyuanxinxi).setOnClickListener(this);
			findViewById(R.id.huoyuanxinxi).setOnClickListener(this);
			findViewById(R.id.zhuanxianxinxi).setOnClickListener(this);
			findViewById(R.id.wodehuoxun).setOnClickListener(this);
			findViewById(R.id.wodechexun).setOnClickListener(this);
			findViewById(R.id.refresh).setOnClickListener(this);

			mCurrentUser = ((MyApp) getApplication()).getCurrentUser();

			if (mCurrentUser.type.equals("C")) {
				// 公司
			} else {
				// 司机
			}
		} catch (Exception e) {
		}
	}

	@Override
	public void onBackPressed() {
		MainTab.tabHost.setCurrentTabByTag("home");
	}

	@Override
	public void onClick(View v) {
		Class activity = null;
		Intent i;
		switch (v.getId()) {
		case R.id.ziliaoweihu: {
			activity = MyPage.class;
			i = new Intent(this, activity);
			startActivity(i);
		}
			break;
		case R.id.xiugaimima: {
			activity = ChangePassword.class;
			i = new Intent(this, activity);
			startActivity(i);
		}
			break;
		case R.id.zhaohuimima: {
			activity = UserBuchong.class;
			i = new Intent(this, activity);
			startActivity(i);
		}
			break;

		case R.id.huoyuanxinxi: {
			activity = MyCollectGood.class;
			i = new Intent(this, activity);
			startActivity(i);
		}
			break;
		case R.id.cheyuanxinxi: {
			activity = MyCollectCar.class;
			i = new Intent(this, activity);
			startActivity(i);
		}
			break;
		case R.id.zhuanxianxinxi: {
			activity = MyCollectLine.class;
			i = new Intent(this, activity);
			startActivity(i);
		}
			break;
		case R.id.wodehuoxun: {
			activity = GetMyGood.class;
			i = new Intent(this, activity);
			startActivity(i);
		}
			break;
		case R.id.wodechexun: {
			activity = GetMyCar.class;
			i = new Intent(this, activity);
			startActivity(i);
		}
			break;
		case R.id.refresh: {
			new AsyncTask<Void, Void, Object>() {

				protected void onPostExecute(Object result) {
					if (result instanceof Exception) {
						Exception e = (Exception) result;
						Toast.makeText(My156.this, "刷新失败，请稍候再试",
								Toast.LENGTH_LONG).show();
					} else {
						SoapPrimitive so = (SoapPrimitive) result;
						mBalance.setText(String.format("我的物银卡（余额： %s RMB）",
								so.toString()));
					}
				};

				@Override
				protected Object doInBackground(Void... params) {
					try {
						return mWebServiceClient
								.common_getBalance(mCertificate);
					} catch (IOException e) {
						return e;
					} catch (XmlPullParserException e) {
						return e;
					}
				}
			}.execute();
		}
			break;
		}
	}

	private void getMyPosition() {
		locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);
		List<String> providers = locationManager.getProviders(true);
		for (String item : providers) {
			Location loc = locationManager.getLastKnownLocation(item);
			if (loc != null) {
				myLatitude = String.valueOf(loc.getLatitude());
				myLongitude = String.valueOf(loc.getLongitude());
			}
			updateCurrentLocationView(myLatitude, myLongitude);
		}

		openGPSSettings();
	}

	private void updateCurrentLocationView(String lat, String lon) {
		// mCurrentLocation.setText(String.format("当前位置: 纬度: %.3f, 精度: %.3f",
		// Double.valueOf(lat), Double.valueOf(lon)));
	}

	private static final int GPS_FAILED = 0;
	private static final int NETWORK_FAILED = 1;
	private static final String TAG = null;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			// case GPS_FAILED:
			// if (TextUtils.isEmpty(myLongitude)) {
			// locationManager.removeUpdates(locationListener);
			// startFetchingLocation(LocationManager.NETWORK_PROVIDER);
			// }
			// break;
			case NETWORK_FAILED:
			default:
				if (TextUtils.isEmpty(myLongitude)) {
					locationManager.removeUpdates(locationListener);
					// Toast.makeText(FindPlace.this, "定位失败", Toast.LENGTH_LONG)
					// .show();
					AlertDialog.Builder builer = new AlertDialog.Builder(
							My156.this);
					builer.setMessage("定位失败，请您确保你已经连接网络或者已经开启GPS");
					builer.setNegativeButton("知道了", null);
					builer.show();
				}
				break;
			}
		}
	};

	LocationListener locationListener = new MyLocationListener();
	LocationListener locationListener1 = new MyLocationListener();

	class MyLocationListener implements LocationListener {
		public void onLocationChanged(Location location) {
			Log.d(TAG, "location.longitude: " + location.getLongitude()
					+ ", latitude: " + location.getLatitude());
			myLongitude = String.valueOf(location.getLongitude());
			myLatitude = String.valueOf(location.getLatitude());
			updateCurrentLocationView(myLatitude, myLongitude);
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			Log.d(TAG, "onStatusChanged: provider: " + provider + ", status: "
					+ status);
		}

		public void onProviderEnabled(String provider) {
			Log.d(TAG, "onProviderEnabled");
		}

		public void onProviderDisabled(String provider) {
			Log.d(TAG, "onProviderDisabled");
		}
	};

	private void startFetchingLocation(String provider) {
		// LocationManager.GPS_PROVIDER
		// LocationManager.NETWORK_PROVIDER;
		String providers = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		// 03-10 22:39:58.207: E/AndroidRuntime(20101): Caused by:
		// java.lang.IllegalArgumentException: provider=network,gps
		String[] items = providers.split(",");
		try {
			for (String item : items) {
				locationManager.requestLocationUpdates(item, 0, 0,
						new MyLocationListener());
				mHandler.sendMessageDelayed(
						Message.obtain(mHandler, NETWORK_FAILED), 5000);
			}
		} catch (Exception e) {
		}

		// locationManager
		// .requestLocationUpdates(provider, 0, 0, locationListener);
		// if (provider.equals(LocationManager.GPS_PROVIDER)) {
		// mHandler.sendMessageDelayed(Message.obtain(mHandler, GPS_FAILED),
		// 4000);
		// } else if (provider.equals(LocationManager.NETWORK_PROVIDER)) {
		// mHandler.sendMessageDelayed(
		// Message.obtain(mHandler, NETWORK_FAILED), 2000);
		// }
	}

	private void openGPSSettings() {
		LocationManager alm = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);
		if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
			Toast.makeText(this, "GPS已经开启", Toast.LENGTH_SHORT).show();

			startFetchingLocation(LocationManager.GPS_PROVIDER);
		} else {
			AlertDialog.Builder builer = new Builder(this);
			builer.setMessage("GPS尚未开启，前去开启？");
			builer.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent myIntent = new Intent(
									Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							startActivityForResult(myIntent, 0);
						}
					});
			builer.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							startFetchingLocation(LocationManager.NETWORK_PROVIDER);
						}
					});
			builer.show();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d(TAG, "requsetCode: " + requestCode + ", resultCode: "
				+ resultCode);
		String provider = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		if (provider != null) {
			Log.v(TAG, " Location providers: " + provider);
			// 03-10 22:39:58.207: E/AndroidRuntime(20101): Caused by:
			// java.lang.IllegalArgumentException: provider=network,gps

			if (provider.contains("gps")) {
				startFetchingLocation(LocationManager.GPS_PROVIDER);
			} else if (provider.contains("network")) {
				startFetchingLocation(LocationManager.NETWORK_PROVIDER);
			}
		} else {
			Toast.makeText(this, "无法获取到您的位置，请开启GPS或者网络", Toast.LENGTH_SHORT)
					.show();
		}
	}
}
